const KPoint = require('../models/kPoint');
const Article = require('../models/article');
const Sequelize = require('sequelize')
//知识点与文章 一对多关系
KPoint.hasMany(Article,{foreignKey:'kp_id',sourceKey:'kp_id'});
Article.belongsTo(KPoint,{foreignKey:'kp_id',targetKey:'kp_id'});

class ArticlesCtl{
  async find(ctx){
    const currentPage = ctx.request.query.currentPage
    const {count,rows} = await Article.findAndCountAll({
      include:[{
        attributes:[],
        model:KPoint,
        required: true,
      }],
      attributes:['article_id','title','content','kp_id',[Sequelize.col('KPoint.kp_name'), 'kp_name']],
      limit:  10,
      offset: (currentPage - 1) * 10
    })
    ctx.body = {
      status:200,
      msg:'success',
      data:{
        count,
        data:rows
      }
    }
  }
  async findAll(ctx){
    const {count,rows} = await Article.findAndCountAll({
      include:[{
        attributes:[],
        model:KPoint,
        required: true,
      }],
      attributes:['article_id','title','content','kp_id',[Sequelize.col('KPoint.kp_name'), 'kp_name']],
    })
    ctx.body = {
      status:200,
      msg:'success',
      data:{
        count,
        data:rows
      }
    }
  }
  async create(ctx){
    const {kp_id,title,content} = ctx.request.body;
    const article = await Article.create({
      title,
      content,
      kp_id
    });
    ctx.body = article;
  }
  async update(ctx){
    const article = await Article.findOne({
      where:{
        article_id:ctx.params.id
      }
    })
    if(!article){
      ctx.throw(404,'文章不存在')
    }
    const {kp_id,title,content} = ctx.request.body;
    await article.update({
      kp_id,title,content
    },{
      where:{
        article_id:ctx.params.id
      }
    })
    ctx.body = article
  }
  async delete(ctx){
    const article = await Article.findOne({
      where:{
        article_id:ctx.params.id
      }
    })
    if(!article){
      ctx.throw(404,'文章不存在')
    }
    await article.destroy();
    ctx.status = 204
  }
}

module.exports = new ArticlesCtl();